package com.luoyx.vjsb.authority.util;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luoyx.vjsb.common.exception.MyException;
import com.luoyx.vjsb.core.entity.SysUser;
import com.luoyx.vjsb.core.service.ISysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *
 * </p>
 *
 * @author luoyuanxiang
 * @date 2020/5/4 16:48
 */
@Component
public class SecurityUtil {

    @Resource
    private ISysUserService iSysUserService;

    /**
     * 获取当前登录用户
     * @return SysUser
     */
    public SysUser getCurrUser(){

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if("anonymousUser".equals(principal.toString())){
            throw new MyException("未检测到登录用户");
        }
        UserDetails user = (UserDetails) principal;
        return iSysUserService.getOne(new QueryWrapper<SysUser>().eq("username", user.getUsername()));
    }

    /**
     * 通过用户名获取用户拥有权限
     * @param username 用户名
     */
    public List<GrantedAuthority> getCurrUserPerms(String username){
        List<GrantedAuthority> authorities = new ArrayList<>();
        SysUser user = iSysUserService.getOne(new QueryWrapper<SysUser>().eq("username", username));
        Set<String> permissions = UserUtil.getPermissions(user);
        Set<String> roles = UserUtil.getRoles(user);
        assert permissions != null;
        permissions.forEach(s -> authorities.add(new SimpleGrantedAuthority(s)));
        assert roles != null;
        roles.forEach(role -> authorities.add(new SimpleGrantedAuthority("ROLE_" + role)));
        return authorities;
    }
}
